package com.sprouting.ops.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 启动跨域
 *
 * 注解 ConditionalOnProperty 说明，prefix为配置文件中的前缀，name为配置的名字，havingValue是与配置的值对比值,当两个值相同返回true,配置类生效
 * 该注解可以放到类上，也可以放到方法上。
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2023/3/16 10:54
 */
@Configuration
@Slf4j
// @ConditionalOnProperty(prefix = "ops", name = "customize.cors.enabled", havingValue = "true") 两种方式都可以
@ConditionalOnProperty(value = "ops.customize.cors.enabled", havingValue = "true")
public class CorsConfig {


    /**
     * 注册跨域
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        log.info("[跨域] 已开启跨域");
        return new CorsFilter(source);
    }

    /**
     * 配置跨域信息
     * @return
     */
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }
}
